package com.bingo.rbac.common;

import com.bingo.rbac.exception.ParamException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.Model;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 统一异常处理类
 * @author bingo
 * @create 2017-12-02 17:58
 **/
public class SpringExceptionResolver implements HandlerExceptionResolver{
private Logger logger = LoggerFactory.getLogger(SpringExceptionResolver.class);

    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
        String url  = httpServletRequest.getRequestURI();
        logger.info("bingo-----------"+url);
        ModelAndView mv = null;
        String defaultMessage  = "system error";
        if(url.endsWith(Const.URL_SUFFIX_JSON)){
            if(e instanceof ParamException){
                logger.info("------jsondRequest");
                ServerResponse serverResponse = ServerResponse.createServerResponseByFailure(e.getMessage());
                httpServletResponse.setCharacterEncoding("UTF-8");
                httpServletResponse.setContentType("text/json;charset=utf-8");
                PrintWriter out= null;
                try {
                    out = httpServletResponse.getWriter();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
                out.println(serverResponse.getMap().toString());
                out.flush();
                out.close();
                return null;
                }
                else {
                logger.info("json:"+"else");
                ServerResponse serverResponse = ServerResponse.createServerResponseByFailure(defaultMessage);
                mv = new ModelAndView("jsonView",serverResponse.getMap());
            }
        } else if(url.endsWith(Const.URL_SUFFIX_PAGE)){
            if(e instanceof ParamException){
                ServerResponse serverResponse = ServerResponse.createServerResponseByFailure(e.getMessage());
                mv = new ModelAndView("exception",serverResponse.getMap());
            }
            else{
                ServerResponse serverResponse = ServerResponse.createServerResponseByFailure(defaultMessage);
                mv = new ModelAndView("exception",serverResponse.getMap());
            }
        }
        return mv;
    }
}
